package basic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author G_Y
 * @Date 2021/4/2 14:31
 * @Description: // TODO
 **/
public class PhoneSegmentTest {

    public static void main(String[] args) {
        int obj1 = 1340000;
        int obj2 = 1889969;
        // 模拟 hashMap底层hash算法
        System.out.println((((obj1-1340000)>>16)^(obj1-1340000))&1048576-1);
        System.out.println((((obj2-1340000)>>16)^(obj2-1340000))&1048576-1);
    }

    // 结合需求 及 HashMap底层hash算法实现原理，初始化一个如下的HashMap
    private static Map<Integer, PhoneSegment> phoneSegmentHashMap
            = new HashMap<Integer, PhoneSegment>(1048576, 1);

    // 程序启动时，加载如下方法
    // 初始化 12万 号段 数据 到hash结构
    public void initData2Map() {
        // 获取 数据库 号段值数据 集合
        List<PhoneSegment> list = getAllPhoneSegmentFromDB();
        // 遍历集合，将数据 put到 phoneSegmentHashMap 中
        phoneSegmentHashMap = list.stream().collect(Collectors.toMap(p -> p.getCode()-1340000, p -> p));
    }
    // 从数据库获取 电话号段信息集合
    public List<PhoneSegment> getAllPhoneSegmentFromDB() {
        // DB读取数据，代码略
        return new ArrayList<>();
    }

    // 根据用户的电话号码 从map中 获取 号段信息
    public PhoneSegment getPhoneSegmentByPhone(String phone) {
        String phoneSegmentCode = phone.substring(0, 7);
        PhoneSegment phoneSegment = phoneSegmentHashMap.get(Integer.valueOf(phoneSegmentCode)-1340000);
        return phoneSegment;
    }
}

class PhoneSegment {
    private Integer id;
    private Integer code;
    private String province;
    private String city;
    private String serverType;
    // get set 略

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getServerType() {
        return serverType;
    }

    public void setServerType(String serverType) {
        this.serverType = serverType;
    }
}
